package com.Java.train.business.service.Impl;

import com.Java.train.business.entity.TrainSeat;
import com.Java.train.business.enums.SeatColEnum;
import com.Java.train.business.mapper.TrainSeatMapper;
import com.Java.train.business.service.TrainSeatService;
import com.Java.train.common.response.CommonResp;
import com.Java.train.business.entity.DTO.TrainCarriageDTO;
import com.Java.train.business.req.TrainCarriageQueryReq;
import com.Java.train.common.exception.BusniessException;
import com.Java.train.common.exception.BusniessExceptionEnum;
import com.Java.train.common.response.PageResp;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.Java.train.business.entity.TrainCarriage;
import com.Java.train.business.mapper.TrainCarriageMapper;
import com.Java.train.business.service.TrainCarriageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.Java.train.common.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.date.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Arrays;

/**
* 火车车厢 服务实现类
*
* @author luomoxingchen
* @since 2024-09-22
*/
@Service
public class TrainCarriageServiceImpl extends ServiceImpl<TrainCarriageMapper, TrainCarriage> implements TrainCarriageService {

    private static final Logger LOG = LoggerFactory.getLogger(TrainCarriageService.class);

    @Autowired
    TrainCarriageMapper trainCarriageMapper;
    @Resource
    TrainSeatMapper trainSeatMapper;


    @Override
    public PageResp<TrainCarriageDTO> queryList(TrainCarriageQueryReq trainCarriageQueryReq){
        // 1.获取当前用户id信息
        //        Long id = LoginMemberContext.getId();
        String trainCode = trainCarriageQueryReq.getTrainCode();
        // 2.查询数据库中是否存在当前信息（id）
        LOG.info("查询页码：{}", trainCarriageQueryReq.getPage());
        LOG.info("每页条数：{}", trainCarriageQueryReq.getSize());
        PageHelper.startPage(trainCarriageQueryReq.getPage(),trainCarriageQueryReq.getSize());
        List<TrainCarriage> trainCarriages = null;
        if(StrUtil.isNotBlank(trainCode)){
            trainCarriages = getCarriageByUnique(trainCode);
        }else {
            trainCarriages = list();
        }

        if(trainCarriages == null || CollUtil.isEmpty(trainCarriages)){
            // 返回空列表
            return new PageResp<TrainCarriageDTO>();
//            throw new BusniessException(BusniessExceptionEnum.MEMBER_PASSENGER_NOT_EXITS);
        }


        // 3 分析分页信息
        // 3.1 获取分页总条数和页数
        PageInfo<TrainCarriage> pageInfo = new PageInfo<>(trainCarriages);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // 3.2 转为封装后的返回值并封装到分页返回值中
        List<TrainCarriageDTO> list = BeanUtil.copyToList(trainCarriages, TrainCarriageDTO.class);
        PageResp<TrainCarriageDTO> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        // 4.返回查询到的信息
        return pageResp;
    }

    @Override
    public CommonResp<Object> modify(TrainCarriage trainCarriage) {
        Long id = trainCarriage.getId();
        DateTime dateTime = DateTime.now();

        // 自动生成列数和总座位数
        List<SeatColEnum> colEnums = SeatColEnum.getColsByType(trainCarriage.getSeatType());
        trainCarriage.setColCount(colEnums.size());
        trainCarriage.setSeatCount(trainCarriage.getColCount() * trainCarriage.getLineCount());

        if(ObjectUtil.isNotEmpty(getCarriageByUnique(trainCarriage.getTrainCode(), trainCarriage.getIdx())) && ObjectUtil.isNull(id)){
            throw new BusniessException(BusniessExceptionEnum.BUSINESS_CARRIAGE_ALREADY_EXITS);
        }

        if(ObjectUtil.isNull(id)){
            trainCarriage.setId(SnowFlakeUtil.getSnowFlakeNextId());
            trainCarriage.setCreateTime(dateTime);
            trainCarriage.setUpdateTime(dateTime);
            boolean save = save(trainCarriage);
            return new CommonResp<>(save);
        } else {
            trainCarriage.setUpdateTime(dateTime);
            boolean update = updateById(trainCarriage);
            return new CommonResp<>(update);
        }
    }

    @Override
    public CommonResp<Object> remove(String ids) {
        if(StrUtil.isNotEmpty(ids)){
            String[] array = ids.split(",");
            if(!CollectionUtils.isEmpty(Arrays.asList(array))) {
                // 删除车厢对应的车座信息
                TrainCarriage trainCarriage = getById(array[0]);
                Integer idx = trainCarriage.getIdx();
                LambdaQueryWrapper<TrainSeat> wrapper = new LambdaQueryWrapper<TrainSeat>();
                trainSeatMapper.delete(wrapper.eq(TrainSeat::getCarriageIndex, idx));
                return new CommonResp<>(removeBatchByIds(Arrays.asList(array)));
            }
        }
        return new CommonResp<>("删除成功");
    }


    // 通过唯一键校验查重
    private List<TrainCarriage> getCarriageByUnique(String trainCode) {
        LambdaQueryWrapper<TrainCarriage> wrapper = new LambdaQueryWrapper<>();
        List<TrainCarriage> list = list(wrapper.eq(TrainCarriage::getTrainCode, trainCode));
        return list;
    }

    // 通过唯一键校验查重
    private List<TrainCarriage> getCarriageByUnique(String trainCode, Integer idx) {
        LambdaQueryWrapper<TrainCarriage> wrapper = new LambdaQueryWrapper<>();
        List<TrainCarriage> list = list(wrapper.eq(TrainCarriage::getTrainCode, trainCode).eq(TrainCarriage::getIdx, idx));
        return list;
    }

}


